package com.hsy.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hsy.pojo.User;
import com.hsy.service.UserService;
import com.hsy.service.impl.UserServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 添加用户（含文件上传版本）
 */
            @WebServlet("/AddUserServlet")
            public class AddUserServlet extends HttpServlet {
                private UserService userService = new UserServiceImpl();  // 使用业务层服务

                protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                    response.setContentType("application/json;charset=UTF-8");
                    request.setCharacterEncoding("UTF-8");
                    // 检查请求是否为文件上传
                    if (!ServletFileUpload.isMultipartContent(request)) {
                        writeResponse(response, false, "Invalid form type.");
                        return;
                    }

                    // 创建FileItemFactory
                    FileItemFactory factory = new DiskFileItemFactory();
                    // 使用FileItemFactory创建ServletFileUpload对象
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    String userNumber = null;
                    String nickName = null;
                    String telephone = null;
                    String password = null;
                    String avatarAddress = null;

                    try {
                        // 解析请求中的所有表单项
                        List<FileItem> items = upload.parseRequest(request);

                        for (FileItem item : items) {
                            if (item.isFormField()) {
                                // 普通表单字段
                                switch (item.getFieldName()) {
                                    case "userNumber":
                                        userNumber = item.getString();
                                        break;
                                    case "nickName":
//                                        nickName = item.getString();
                                        nickName = item.getString("UTF-8"); // 指定字符集编码方式，可以防止添加中文时乱码
                                        break;
                                    case "telephone":
                                        telephone = item.getString();
                                        break;
                                    case "password":
                                        password = item.getString();
                                        break;
                                }
                            } else {
                                // 文件上传字段
                                upload.setHeaderEncoding("UTF-8");  // 确保上传表单中的文件名不会因为编码不一致而导致乱码问题
                                if ("avatar".equals(item.getFieldName())) {
                                    String fileName = FilenameUtils.getName(item.getName());
                                    if (fileName != null && !fileName.isEmpty()) {
                                        // 保存文件到服务器（这种方式在本地的资源管理器是看不到的，所以一旦重启TomCat图片就失效了）
                                        String filePath = getServletContext().getRealPath("/static/images/") + fileName;
                                        File file = new File(filePath);
                                        item.write(file);  // 保存文件
                                        avatarAddress = "/static/images/" + fileName; // 文件的相对路径
                                    }
                                }
                            }
                        }

            // 创建用户对象
            User user = new User(userNumber, nickName, telephone, password, avatarAddress);

            Map<String, Object> responseData = new HashMap<>();
            if (userService.checkUserNotExist(user)) {
                // 如果用户不存在，则插入
                int result = userService.insert(user);
                if (result > 0) {
                    responseData.put("success", true);
                    responseData.put("message", "用户新增成功");
                } else {
                    responseData.put("success", false);
                    responseData.put("message", "用户新增失败，插入数据库时出现问题");
                }
            } else {
                responseData.put("success", false);
                responseData.put("message", "用户已存在，无法新增");
            }

            // 返回响应数据
            String responseJson = new ObjectMapper().writeValueAsString(responseData);
            writeResponse(response, responseJson);

        } catch (FileUploadException e) {
            writeResponse(response, false, "Error during file upload.");
        } catch (Exception e) {
            writeResponse(response, false, "Unknown error.");
        }
    }

    // 用于返回JSON响应的辅助方法
    private void writeResponse(HttpServletResponse response, String jsonResponse) throws IOException {
        PrintWriter writer = response.getWriter();
        writer.write(jsonResponse);
        writer.flush();
        writer.close();
    }

    // 用于返回JSON响应的辅助方法（错误信息）
    private void writeResponse(HttpServletResponse response, boolean success, String message) throws IOException {
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("success", success);
        responseData.put("message", message);
        String jsonResponse = new ObjectMapper().writeValueAsString(responseData);
        writeResponse(response, jsonResponse);
    }
}
